package com.novel.service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.novel.common.event.UserRecommendEvent;
import com.novel.common.event.UserRecommendPojo;
import com.novel.common.exception.CustomerException;
import com.novel.common.vo.AliPayVo;
import com.novel.config.AliPayConfig;
import com.novel.mapper.RechargeMapper;
import com.novel.pojo.system.Order;
import com.novel.pojo.system.Recharge;
import com.novel.pojo.system.User;
import com.novel.utils.GsonTool;
import com.novel.utils.OrderNoUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.UUID;

@Slf4j
@Service
public class AliPayService {

    @Autowired
    private OrderService orderService;

    @Autowired
    private AlipayClient alipayClient;

    @Autowired
    private ApplicationEventPublisher publisher;

    @Autowired
    private RechargeMapper rechargeMapper;

    @Transactional
    public String pay(User user, String ipAddress, String id) throws AlipayApiException {

        Recharge recharge = rechargeMapper.selectByPrimaryKey(id);

        Double cost = recharge.getCost();
        Integer balance = recharge.getBalance();

        //封装数据
        Order order = new Order();
        order.setUserId(user.getUserId());
        order.setCreatedIp(ipAddress);
        order.setCost(cost);
        order.setBalance(balance);
        order.setId(UUID.randomUUID().toString());
        order.setOrderNo(OrderNoUtils.generate());
        order.setCreatedTime(new Date());
        order.setStatus(0);

        //创建订单
        orderService.createdOrder(order);

        //支付宝沙箱支付
        AliPayVo vo = new AliPayVo();
        vo.setOut_trade_no(order.getOrderNo());
        vo.setTotal_amount(String.valueOf(cost));
        vo.setSubject("购买书币");
        vo.setProduct_code("FAST_INSTANT_TRADE_PAY"); //这个是固定的
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setBizContent(GsonTool.toJson(vo));
        request.setReturnUrl(AliPayConfig.return_url);
        request.setNotifyUrl(AliPayConfig.notify_url);
        // 执行支付宝请求，其实就是httpclient请求
        // 注意这里使用的是AlipayTradePagePayRequest，返回的是response.getBody()，与自定义二维码不同
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
        if (response.isSuccess()) {
            //订单支付成功，修改订单状态
            orderService.payOrder(order.getOrderNo());

            //检查充值的数额,是否赠送推荐票,使用Spring时间监听器异步执行
            UserRecommendPojo recommendPojo = new UserRecommendPojo();
            recommendPojo.setCost(cost.intValue());
            recommendPojo.setUserId(order.getUserId());
            UserRecommendEvent event = new UserRecommendEvent(this, recommendPojo);
            publisher.publishEvent(event);
            return response.getBody();
        }
        throw new CustomerException("支付异常");
    }

}